// 预处理中间件
package middleware

import (
	"context"
	"time"

	"advertising/config/redis"
	"advertising/internal/define"

	"192.168.1.75/go-pkg/errorx"
	"192.168.1.75/go-pkg/response"
	"github.com/gin-gonic/gin"
)

// AccessCheck 检验登录
func AccessCheck() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.GetHeader("Authorization")
		rdb := redis.NewDB()
		// 获取会话参数
		timeoutCtx, cancel := context.WithTimeout(context.Background(), time.Second*3)
		defer cancel()

		exists, _ := rdb.HExists(context.Background(), define.RedisUserLoginTokenPrefix+token, "user_id").Result()
		if token == "" || !exists {
			response.JSON(c, nil, errorx.New("请重新登录", 100001))
			c.Abort()
			return
		}
		valueMap, _ := rdb.HGetAll(timeoutCtx, define.RedisUserLoginTokenPrefix+token).Result()
		c.Set("user_id", valueMap["user_id"])
		c.Set("username", valueMap["username"])
		c.Set("merchant_id", valueMap["merchant_id"])
		c.Set("merchant_name", valueMap["merchant_name"])
		c.Set("role_id", valueMap["role_id"])
		c.Set("merchant_path", valueMap["merchant_path"])
		// …… 获取其他参数
		c.Next()
	}
}
